<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Product extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'slug',
        'description',
        'long_description',
        'short_description',
        'sku',
        'price',
        'compare_price',
        'cost_price',
        'stock_quantity',
        'low_stock_threshold',
        'weight',
        'length',
        'width',
        'height',
        'brand',
        'model',
        'specifications',
        'features',
        'tags',
        'is_active',
        'is_featured',
        'product_type',
        'is_digital',
        'requires_shipping',
        'sort_order',
        'published_at',
        'template_id',
        'meta_data',
        'meta_title',
        'meta_description',
        'meta_keywords',
        'canonical_url',
        'has_custom_variants',
        'default_specifications',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'compare_price' => 'decimal:2',
        'cost_price' => 'decimal:2',
        'specifications' => 'array',
        'features' => 'array',
        'tags' => 'array',
        'is_active' => 'boolean',
        'is_featured' => 'boolean',
        'is_digital' => 'boolean',
        'requires_shipping' => 'boolean',
        'has_custom_variants' => 'boolean',
        'published_at' => 'datetime',
        'meta_data' => 'array',
        'meta_keywords' => 'array',
        'default_specifications' => 'array',
        'deleted_at' => 'datetime',
    ];

    protected $appends = ['image', 'technical_specs'];

    /**
     * 自动生成slug
     */
    protected static function boot()
    {
        parent::boot();
        
        static::creating(function ($product) {
            if (empty($product->slug)) {
                $product->slug = Str::slug($product->name);
            }
        });
    }

    /**
     * 分类关联
     */
    public function categories(): BelongsToMany
    {
        return $this->belongsToMany(Category::class, 'product_categories')
                    ->withPivot('is_primary', 'sort_order')
                    ->withTimestamps();
    }

    /**
     * 主分类
     */
    public function primaryCategory()
    {
        return $this->categories()->wherePivot('is_primary', true)->first();
    }

    /**
     * 产品图片
     */
    public function images(): HasMany
    {
        return $this->hasMany(ProductImage::class);
    }

    /**
     * 获取产品主图片
     */
    public function getImageAttribute()
    {
        $primaryImage = $this->images()->where('is_primary', true)->first();
        return $primaryImage ? $primaryImage->image_path : null;
    }

    /**
     * 技术规格访问器
     */
    public function getTechnicalSpecsAttribute()
    {
        return $this->meta_data['technical_specs'] ?? [];
    }

    /**
     * 产品变体
     */
    public function variants(): HasMany
    {
        return $this->hasMany(ProductVariant::class);
    }

    /**
     * 规格模板关联
     */
    public function template(): BelongsTo
    {
        return $this->belongsTo(SpecificationTemplate::class, 'template_id');
    }

    /**
     * 默认变体
     */
    public function defaultVariant()
    {
        return $this->variants()->where('is_default', true)->first();
    }

    /**
     * 变体属性
     */
    public function variantAttributes(): HasMany
    {
        return $this->hasMany(VariantAttribute::class);
    }

    /**
     * 主图片
     */
    public function primaryImage()
    {
        return $this->images()->where('is_primary', true)->first();
    }

    /**
     * 检查是否有库存
     */
    public function inStock(): bool
    {
        return $this->stock_quantity > 0;
    }

    /**
     * 检查是否低库存
     */
    public function isLowStock(): bool
    {
        return $this->stock_quantity <= $this->low_stock_threshold;
    }

    /**
     * 获取折扣百分比
     */
    public function getDiscountPercentageAttribute(): ?float
    {
        if (!$this->compare_price || $this->compare_price <= $this->price) {
            return null;
        }
        
        return round((($this->compare_price - $this->price) / $this->compare_price) * 100, 2);
    }

    /**
     * 作用域：激活的产品
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * 作用域：推荐产品
     */
    public function scopeFeatured($query)
    {
        return $query->where('is_featured', true);
    }

    /**
     * 作用域：有库存
     */
    public function scopeInStock($query)
    {
        return $query->where('stock_quantity', '>', 0);
    }

    /**
     * 作用域：已发布
     */
    public function scopePublished($query)
    {
        return $query->whereNotNull('published_at')
                    ->where('published_at', '<=', now());
    }

    /**
     * 作用域：按价格排序
     */
    public function scopeOrderByPrice($query, $direction = 'asc')
    {
        return $query->orderBy('price', $direction);
    }

    /**
     * 作用域：按品牌筛选
     */
    public function scopeByBrand($query, $brand)
    {
        return $query->where('brand', $brand);
    }

    /**
     * 作用域：单规格产品
     */
    public function scopeSingleVariant($query)
    {
        return $query->where('product_type', 'single');
    }

    /**
     * 作用域：多规格产品
     */
    public function scopeMultiVariant($query)
    {
        return $query->where('product_type', 'multi_variant');
    }

    /**
     * 判断是否为单规格产品
     */
    public function isSingleVariant(): bool
    {
        return $this->product_type === 'single';
    }

    /**
     * 判断是否为多规格产品
     */
    public function isMultiVariant(): bool
    {
        return $this->product_type === 'multi_variant';
    }
}
